import {Component, OnInit, ViewChild} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzModalService} from 'ng-zorro-antd/modal';
import {SelectDeviceComponent} from '../select-device/select-device.component';
import {Router} from '@angular/router';
import {from, Observable, pipe, Subject} from 'rxjs';
import {debounceTime, delay} from 'rxjs/operators';
import { CommonService } from '../../../../services-common/common.service';
import {UsedStorePService} from '../../used-store-p.service';
import {ChannelOccupy, CommodityStatus, DeviceStatus, UserType} from '../../used-store-manage.pipe';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {Clipboard} from '@angular/cdk/clipboard';
import {PermissionService} from '../../../../service/permission.service';
import {UsedStoreZservice} from '../../used-store-zservice';
import { format, formatDistance, formatRelative, subDays } from 'date-fns'

interface TrackModal {
  visible: boolean; // 模态框显隐
  loading: boolean; // 按钮是否加载中
  id: string; // id
  url: string; // 文件
  remark: string; // 跟进内容
  file: any; // 跟进文件
}

@Component({
  selector: 'app-commodity-list',
  templateUrl: './commodity-list.component.html',
  styleUrls: ['./commodity-list.component.scss']
})
export class CommodityListComponent implements OnInit {
  DEVICESTATUS = DeviceStatus;
  CHANNELOCCUPY = ChannelOccupy;
  @ViewChild('reportModalRef') reportModalRef: any;
  COMMODITYSTATUS = CommodityStatus;
  USERTYPE = UserType;
  query = {
    equipmentCode: '', // 编码
    typeId: [], // 设备品牌
    modelId: [], // 设备型号
    status: [], // 状态
    userType: [], // 适用用户
    colourB: [], // B端成色
    colourC: [], // C端成色
    libraryId: [], // 库位
    clinchTime: null, // 成交入库时间
    up: null, // 上架时间
    page: 1, // 当前页
    pageSize: 20, // 分页大小
  };
  listOfData = {
    page: 1,
    total: 100,
    pageSize: 20,
    records: []
  };
  modal = {
    modalVisible: false,
    operationType: '',
    loading: false,
  };
  formData = {
    id: '',
    date: '',
    productId: '',
    registerCount: 0,
    rechargeAmount: 0,
  };
  appOptions: any[] = [];
  // 品牌待选项
  brandOptions: any[] = [];
  // 机型待选项
  typeOptions: any[] = [];
  //  跟进
  trackModal: TrackModal = {
    visible: false,
    loading: false,
    id: '',
    url: '',
    remark: '',
    file: [],
  };
  trackHistoryList: any[] = [];
  changeChannel = {
    visible: false,
    equipmentCode: '',
  };
  // 库位待选项
  locationOptions: any[] = [];
  // 成色待选项
  colourBOptions: any[] = [];
  colourOptions: any[] = [];
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    console.log(file);
    this.trackModal.file = [file];
    return false;
  };

  /**
   * 勾选 Table Checked
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  checkedOriginList: any[] = [];
  /**
   * 审核 Modal
   * ----------------------------------------------------------------
   */
  isExamineVisible: boolean = false;
  examineObjs = {
    auditContent: ''
  };

  // 导出
  exportLoading = false;

  /**
   * 改价
   */
  priceChangeVisible = false;
  priceChangeId: number = 0;

  // 延迟B端上架
  delayPutVisible = false;
  delayPutLoading = false;
  delayPutTime: any = null;

  constructor(
    private nzMessageService: NzMessageService,
    private nzModalService: NzModalService,
    private router: Router,
    private usedStorePService: UsedStorePService,
    private usedStoreZservice: UsedStoreZservice,
    public clipboard: Clipboard,
    private commonService: CommonService,
    public permissionService: PermissionService
  ) {
  }

  async ngOnInit() {
    await this.usedStorePService.dictData('machine_condition').then((res: any) => {
      if (res.code === 0) {
        this.colourOptions = res.data.list.records;
      }
    });
    await this.usedStorePService.dictData('machine_condition_b').then((res: any) => {
      if (res.code === 0) {
        this.colourBOptions = res.data.list.records;
      }
    });
    await this.usedStoreZservice.recycleLibraryList({page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.locationOptions = res.data.records;
      }
    });
    this.queryList();
    this.usedStorePService.getBrandList().then((res: any) => {
      if (res.code === 0) {
        this.brandOptions = res.data.records;
      }
    });
  }

  copy() {
    this.clipboard.copy(this.changeChannel.equipmentCode);
    this.nzMessageService.success('复制成功');
  }

  getTypeList() {
    this.query.modelId = [];
    if (!this.query.typeId.join(',')) {
      this.typeOptions = [];
      return;
    }
    this.usedStorePService.getTypeList(this.query.typeId.join(',')).then((res: any) => {
      if (res.code === 0) {
        this.typeOptions = res.data.records;
      }
    });
  }


  queryBtn() {
    this.query.page = 1;
    this.queryList();
  }

  resetQuery() {
    this.query = {
      equipmentCode: '', // 编码
      typeId: [], // 设备品牌
      modelId: [], // 设备型号
      status: [], // 状态
      userType: [], // 适用用户
      colourB: [], // B端成色
      colourC: [], // C端成色
      libraryId: [], // 库位
      clinchTime: null, // 成交入库时间
      up: null, // 上架时间
      page: 1, // 当前页
      pageSize: 20, // 分页大小
    };
    this.queryList();
  }

  // 查询列表
  queryList(): void {
    this.usedStorePService.getCommodityList({
      ...this.query,
      // @ts-ignore
      createTime: this.usedStorePService.formatTime(this.query.up ? this.query.up[0] : '', 'date'),
      // @ts-ignore
      endTime: this.usedStorePService.formatTime(this.query.up ? this.query.up[1] : '', 'date'),
      // @ts-ignore
      clinchTime: this.usedStorePService.formatTime(this.query.clinchTime ? this.query.clinchTime[0] : '', 'date'),
      // @ts-ignore
      clinchEndTime: this.usedStorePService.formatTime(this.query.clinchTime ? this.query.clinchTime[1] : '', 'date'),
      typeId: this.query.typeId.join(','),
      modelId: this.query.modelId.join(','),
      status: this.query.status.join(','),
      userType: this.query.userType.join(','),
      colourIdB: this.query.colourB.join(','),
      colourId: this.query.colourC.join(','),
      libraryId: this.query.libraryId.join(','),
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
      }
    });
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.queryList();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.queryList();
  }

  // 删除
  deleteRow(id: any) {
    // this.(id).then((res: any) => {
    //   if (res.code === 0) {
    //     this.nzMessageService.success('删除成功');
    //     this.queryList();
    //   }
    // });
  }

  // 放到二手商城销售或者取回
  changeUsedChannel(status: 0 | 2) {
    this.usedStorePService.channelOccupy(this.changeChannel.equipmentCode, 0).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.queryList();
        this.hideUsedChannel();
      }
    });
  }

  showUsedChannel(data: any) {
    this.changeChannel.equipmentCode = data.equipmentCode;
    this.changeChannel.visible = true;
  }

  hideUsedChannel() {
    this.changeChannel.equipmentCode = '';
    this.changeChannel.visible = false;
  }

  view(data: any) {
    // this.router.navigate(['/used-store/usedCommodityInfo'], {queryParams: {id: data.id}});
  }

  changeStatus(data: any, status: any) {
    // this.nzModalService.confirm({
    //   nzTitle: '<i>提示</i>',
    //   nzContent: `<b>${status === 0 ? '确认上架？' : '确认下架？'}</b>`,
    //   nzOnOk: () => {
    //   }
    // });

    this.usedStorePService.changeCommodityStatus(data.id, status).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success(status === 0 ? '上架成功' : '下架成功');
        this.queryList();
      }
    });
  }

  add() {
    const modal = this.nzModalService.create({
      nzTitle: '选择设备',
      nzContent: SelectDeviceComponent,
      nzFooter: null,
      nzWidth: '960px',
      nzMaskClosable: false,
    });
    modal.afterClose.toPromise().then(res => {
      if (res?.refresh) {
        this.queryList();
      }
    });
  }

  // 显示跟进模态框
  showTrackModal(id: string) {
    this.usedStorePService.outStoreHistory(id, 8, 2).then(res => {
      this.trackHistoryList = res.data.records;
      this.trackModal.id = id;
      this.trackModal.visible = true;
    });
  }

  // 隐藏跟进模态框
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.loading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.usedStorePService.httpPost(this.usedStorePService.serviceUrl.fileUpload, file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.url = res.data;
          }
        });
      }
      // enclosure	附件
      // content	跟进内容
      // type	1、订单 2、售后 3、客户 4、出库 5直降  6退税 7机器 8商品
      // relationInformation	关联id
      // remarks	跟进备注
      // modelId	类型 1旧的表示二手回收 2表示二手商城 3表示二手回收
      this.usedStorePService.outStoreTrack({
        enclosure: this.trackModal.url,
        content: this.trackModal.remark,
        type: 8,
        relationInformation: this.trackModal.id,
        remarks: '',
        modelId: 2,
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.trackModal = {
            visible: false,
            loading: false,
            id: '',
            url: '',
            remark: '',
            file: [],
          };
        } else {
          this.trackModal.loading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.trackModal = {
        visible: false,
        loading: false,
        id: '',
        url: '',
        remark: '',
        file: [],
      };
    }
  }

  moreThanSeven(time: any) {
    if (+new Date() - +new Date(time) > (1000 * 3600 * 24 * 7)) {
      return true;
    }
    return false;
  }

  showReportModal(phoneCode: any) {
    const params = {
      phoneCode
    };
    this.reportModalRef.loadData(params);
    this.reportModalRef.isVisible = true;
  }

  /**
   * ----------------------------------------------------------------
   * 表格勾选操作
   * ----------------------------------------------------------------
   */
  updateCheckedSet(item: any, checked: boolean): void {
    if (checked) {
      this.checkedOriginList.push(item);
      this.setOfCheckedId.add(item.id);
    } else {
      this.setOfCheckedId.delete(item.id);
    }
  }

  onItemChecked(item: any, checked: boolean): void {
    this.updateCheckedSet(item, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    // this.listOfCurrentPageData.filter((tag: any) => [0, 7].includes(tag.status)).forEach(item => this.updateCheckedSet(item, value));
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    let tempArr = this.listOfCurrentPageData.filter((tag: any) => [0, 7].includes(tag.status));
    this.checked = tempArr.length > 0 && tempArr.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = tempArr.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  /**
   * ----------
   * 审核
   */
  examineShowModal() {
    if (!this.setOfCheckedId.size) {
      this.nzMessageService.warning('请先选择所需审核项!');
      return;
    }
    this.examineObjs.auditContent = '';
    this.isExamineVisible = true;
  }

  // 批量审核
  async submitExamine(type: number) {
    if (type === 6 && !this.examineObjs.auditContent) {
      this.nzMessageService.warning('请输入审核意见!');
      return;
    }
    const selStrs: number[] = [];
    Array.from(this.setOfCheckedId).forEach(id => {
      if (this.checkedOriginList.some(item => item.id === id && item.status === 7)) {
        selStrs.push(id);
      }
    });
    if (!selStrs.length) {
      this.nzMessageService.warning('待审核数据条目不能为空!');
      return;
    }
    const params = {
      ...this.examineObjs,
      ids: selStrs.join(','),
      status: type
    };

    const res: any = await this.usedStorePService.goodsAuditDatas(params);
    if (res.code === 0) {
      this.nzMessageService.success('操作成功');
      this.isExamineVisible = false;
      this.setOfCheckedId.clear();
      this.queryList();
    } else {
      this.nzMessageService.error(res.message);
    }
  }

  // 批量下架
  async downCommodity() {
    const selStrs: number[] = [];
    Array.from(this.setOfCheckedId).forEach(id => {
      if (this.checkedOriginList.some(item => item.id === id && item.status === 0)) {
        selStrs.push(id);
      }
    });
    if (!selStrs.length) {
      this.nzMessageService.warning('上架中数据条目不能为空!');
      return;
    }
    for (let i = 0; i < selStrs.length; i++) {
      await this.usedStorePService.changeCommodityStatus(selStrs[i], 1);
    }
    this.nzMessageService.success('操作成功');
    this.setOfCheckedId.clear();
    this.checkedOriginList = [];
    this.queryList();
  }

  // 提交审核
  async submitReview(item: any) {
    let params = {
      ids: item.id,
      status: 7
    };
    const res: any = await this.usedStorePService.goodsAuditDatas(params);
    if (res.code === 0) {
      this.nzMessageService.success('操作成功');
      this.queryList();
    } else {
      this.nzMessageService.error(res.message);
    }
  }

  // 导出
  exportTable() {
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ...this.query,
          // @ts-ignore
          createTime: this.usedStorePService.formatTime(this.query.up ? this.query.up[0] : '', 'date'),
          // @ts-ignore
          endTime: this.usedStorePService.formatTime(this.query.up ? this.query.up[1] : '', 'date'),
          // @ts-ignore
          clinchTime: this.usedStorePService.formatTime(this.query.clinchTime ? this.query.clinchTime[0] : '', 'date'),
          // @ts-ignore
          clinchEndTime: this.usedStorePService.formatTime(this.query.clinchTime ? this.query.clinchTime[1] : '', 'date'),
          typeId: this.query.typeId.join(','),
          modelId: this.query.modelId.join(','),
          status: this.query.status.join(','),
          userType: this.query.userType.join(','),
          colourIdB: this.query.colourB.join(','),
          colourId: this.query.colourC.join(','),
          libraryId: this.query.libraryId.join(',')
        }
        this.exportLoading = true;
        const res: any = await this.usedStorePService.exportGoodsData(params);
        this.exportLoading = false;

        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '二手商品');
        } else {
          this.nzMessageService.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 改价
  showPriceModal(item: any) {
    this.priceChangeId = item.id;
    this.priceChangeVisible = true;
  }

  /**
   * 批量上下架
   * @param type 0：上架 1：下架
   */
  async batchUpLowShelves(type: number) {
    if (!this.setOfCheckedId.size) {
      this.nzMessageService.warning('请先选择所需操作项');
      return
    }

    let params = {
      id: [...this.setOfCheckedId].join(','),
      status: type
    }
    const {code, data}: any = await this.usedStorePService.editSecondHandGoodsStatus(params);

    if (code === 0) {
      this.nzMessageService.success(data || '操作成功');
      this.queryList();
    }
  }

  // 批量下架并取消占用
  async batchLowCancelOccupation() {
    if (!this.setOfCheckedId.size) {
      this.nzMessageService.warning('请先选择所需操作项');
      return
    }

    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: `
        <p>确认批量下架并取消二手占用？</p>
        <p class="zdy-modal-text-red">请及时调整该机器的库位信息，并且及时将商品拿到对应的库位，避免库存混乱<p/>
      `,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          cancelOccupy: 1, // 后端判断使用(批量下架并取消占用)
          id: [...this.setOfCheckedId].join(','),
          status: 1
        }
        const {code, data}: any = await this.usedStorePService.editSecondHandGoodsStatus(params);
    
        if (code === 0) {
          this.nzMessageService.success(data || '操作成功');
          this.queryList();
        }
      },
      nzCancelText: '取消'
    });
  }

  // 延迟B端上架
  showDelayPutModal() {
    if (!this.setOfCheckedId.size) {
      this.nzMessageService.warning('请至少选择一个商品');
      return
    }
    this.delayPutTime = null;
    this.delayPutVisible = true;
  }

  async submitDelayPutData() {
    if (!this.delayPutTime) {
      this.nzMessageService.warning('请先选择延迟时间');
      return
    }

    const params = {
      idList: [...this.setOfCheckedId],
      delayTime: format(new Date(this.delayPutTime), 'yyyy-MM-dd HH:mm') + ':00'
    }
    this.delayPutLoading = true;
    const {code, data}: any = await this.usedStorePService.secondUpdateDelayPutData(params);
    this.delayPutLoading = false;

    if (code === 0) {
      this.delayPutVisible = false;
      this.setOfCheckedId.clear();
      this.checkedOriginList = [];
      this.nzMessageService.success(data);
      this.queryList();
    }
  }
}

